<?php
namespace app\index\controller;

use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\SuoHuiModel;
use think\App;
use think\facade\Config;
use think\Db;
use think\Request;

class Qiyuesuo extends Access
{
    protected $sdkClient;
    /**
     * Common constructor.
     * @param App|null $app
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        require_once '../vendor/qiyuesuo/Util.php';
        $this->sdkClient = \Util::getSDk();
    }

    public function callback(Request $request){
        $encrypt = $request->param('content');
        $arr = json_decode($this->getAesCrypt($encrypt), true);

        if(is_array($arr) && isset($arr['contractId'])){
            $bill = FlowBillModel::where(['qysconid'=>$arr['contractId']])->find()->toArray();
            if(!$bill){
                return $this->aaa(222);
            }
            SuoHuiModel::insert([
                'billid'=>$bill['id'],
                'contractId'=>$arr['contractId'],
                'callbackType'=>$arr['callbackType'],
                'callbackname'=>$this->get_callbackname($arr['callbackType']),
                'contractStatus'=>$arr['contractStatus'],
                'tenantName'=> isset($arr['tenantName']) ? $arr['tenantName'] : '',
                'contact'=>isset($arr['contact']) ? $arr['contact'] : '',
                'huistr'=>json_encode($arr),
                'created_at'=>date("Y-m-d H:i:s"),
            ]);

            //合同状态
            //DRAFT	草稿
            //RECALLED	已撤回
            //SIGNING	签署中
            //REJECTED	已退回
            //COMPLETE	已完成
            //EXPIRED	已截止签署
            //FILLING	拟定中
            //FAILED	签署失败
            //INVALIDING	作废中
            //INVALIDED	已作废
            $wanArr = ['RECALLED','REJECTED','COMPLETE','EXPIRED','FAILED','INVALIDED'];
            if(in_array($arr['contractStatus'], $wanArr)){
                Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['qysstate'=>1]);
                //给审核人发起审核消息
                if($arr['contractStatus'] == 'COMPLETE' && $arr['callbackType'] == 'COMPLETE'){
                    //1、更新状态为已签订
                    Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['state'=>1]);

                    //2、下载已签署附件
                    $dir = "../infoasset/".date("Ymd")."/";
                    if(!file_exists($dir)){
                        mkdir($dir);
                    }


                    $qysdicidArr = json_decode($bill['qysdicid'], true);
                    foreach ($qysdicidArr as $ffvv){
                        //$qysdicidArr[] = ['fileid'=>$ffvv['id'],'qysdicid'=>$qysfile['result']['documentId']];
                        $filePath = $dir.$ffvv['qysdicid'].'_'.$bill['id'].'.pdf';
                        $fileid_info = FileModel::where(['id'=>$ffvv['fileid']])->find();
                        $qysdown = (new Qiyuesuo())->downcontract($ffvv['qysdicid'], $filePath);
                        if($qysdown && $qysdown['code'] == 0){
                            $ins = [];
                            $ins['comid'] = $bill['comid'];

                            $newName = str_replace($fileid_info['ext'],'pdf', $fileid_info['name']);
                            $ins['name'] = $newName;
                            $ins['ext'] =  'pdf';
                            $ins['size'] = filesize($filePath);
                            $ins['oripath'] =  $filePath;
                            $ins['created_at'] =  date('Y-m-d H:i:s');
                            $ins['typeid'] = (new Qiyuesuo())->get_filetypeid($bill['modenum'], 2);
                            $ins['table'] = $bill['modenum'];
                            $ins['mid'] = $bill['mid'];
                            $ins_id = FileModel::insertGetId($ins);
                            $encpath =  encrypt($ins_id, 'E', Config::get('service.info_key'));
                            FileModel::where(['id'=>$ins_id])->update(['encpath'=>$encpath]);
                        }else{
                            return $this->aaa(222);
                        }
                    }
                    return 'success';
                }
            }
            return 'success';
        }
        return $this->aaa(222);
    }


    //1-未签 2-已签
    public function get_filetypeid($modenum, $type=1){
        $weiqiananId = 0;
        $yiqiananId = 0;
        if($modenum == 'qian_suo'){
            $weiqiananId = 140;
            $yiqiananId = 141;
        }elseif($modenum == 'contract_nei'){
            $weiqiananId = 111;
            $yiqiananId = 112;
        }elseif($modenum == 'engin_shui'){
            $weiqiananId = 142;
            $yiqiananId = 143;
        }elseif($modenum == 'hou_jie'){
            $weiqiananId = 135;
            $yiqiananId = 136;
        }elseif($modenum == 'hou_shou'){
            $weiqiananId = 137;
            $yiqiananId = 138;
        }
        if($type == 1){
            return $weiqiananId;
        }
        return $yiqiananId;
    }



    /**
     * @param $title //合同名称
     * @param $enantName //业务所属公司
     * @param $jsarr
     * @return mixed|null|string
     */
    public function adddraft($bizid, $title, $enantName, $jsarr){
        $contract = new \Contract();
//        $contract->setBizId($bizid);
        $contract->setSubject($title);
        $contract->setTenantName($enantName);
        $contract->setSend(false);

        $category = new \Category();
        $category->setId($bizid);
        $contract->setCategory($category);

        $signatories = [];
        foreach ($jsarr as $vvv){
            $signatory = new \Signatory();
            $signatory->setTenantType("PERSONAL");
            $signatory->setTenantName($vvv['username']);
            $receiver = new \User();
            $receiver->setContact($vvv['usertel']);
            $receiver->setContactType("MOBILE");
            $signatory->setReceiver($receiver);
            $signatory->setDelaySet("false");
            array_push($signatories, $signatory);
        }
        $contract->setSignatories($signatories);
        $baseRequest = new \ContractDraftRequest($contract);
        $result = $this->sdkClient->service($baseRequest);
        return $result;
    }

    //合同添加附件-单文件
    public function addfile($contractId, $bizid, $enantName, $file_path, $filename, $fileext){
        $addRequest = new \DocumentAddByFileRequest();
        $addRequest->setContractId($contractId);
        $addRequest->setBizId($bizid);
        $addRequest->setTenantName($enantName);


        $file_path = iconv("UTF-8", "GBK", realpath($file_path));
        $file = new \CURLFile($file_path);

        $addRequest->setFile($file);
        $addRequest->setFileSuffix($fileext);
        $addRequest->setTitle($filename);
        $result = $this->sdkClient->service($addRequest);
        return $result;
    }
    //合同添加附件-多文件
    public function addmulfile($contractId, $bizid, $enantName, $filearr){
        $AddMulRequest = new \DocumentAddByMultipleFileRequest();
        $AddMulRequest->setContractId($contractId);
        $AddMulRequest->setBizId($bizid);
        $AddMulRequest->setTenantName($enantName);

        $files = [];
        foreach ($filearr as $vvv){
            $arr = curl_file_create($vvv['oripath'], "", $vvv['name'].'.'.$vvv['ext']);
            array_push($files, $arr);
        }
        $AddMulRequest->setFiles($files);
        $AddMulRequest->setTitle('添加多文件文档');
        $result = $this->sdkClient->service($AddMulRequest);
        return $result;
    }

    //发起合同
    public function addcontract($contractId, $bizid, $enantName){
        $addRequest = new \ContractSendRequest();
        $addRequest->setContractId($contractId);
        $addRequest->setBizId($bizid);
        $addRequest->setTenantName($enantName);
        $result = $this->sdkClient->service($addRequest);
        return $result;
    }

    //下载合同附件
    function downcontract($contractId, $filePath){
        $documentDownloadRequest = new \DocumentDownloadRequest($contractId);
        $result = $this->sdkClient->downloadService($documentDownloadRequest, $filePath);
        return $result;
    }

    //强制结束合同
    public function invalidcontract($contractId){
        $invalidRequest = new \ContractInvalidRequest();
        $invalidRequest->setContractId($contractId);
        $invalidRequest->setReason('筑为流程撤回');
        $invalidRequest->setDeleteDoc(false);
        $invalidRequest->setAutoSign(false);
        $result = $this->sdkClient->service($invalidRequest);
        return $result;
    }

    /**
     * 获取公司下的业务列表信息
     * @param $com
     * @return mixed|null|string
     */
    public function check_yewu_bycom($com){
        $cateRequest = new \CategoryListRequest();
        $cateRequest->setSelectOffset("0");
        $cateRequest->setSelectLimit("10000");
        $cateRequest->setTenantName($com);
        $response = $this->sdkClient->service($cateRequest);
        return $response;
    }

    /**
     * 获取业务详情
     * @param $categoryId
     * @return mixed|null|string
     */
    public function check_yewu_byid($categoryId){
        $cateRequest = new \CategoryDetailRequest();
        $cateRequest->setCategoryId($categoryId);
        $response = $this->sdkClient->service($cateRequest);
        return $response;
    }

    /**
     * 解密回调信息
     * @param string $encrypt
     * @return string
     */
    public function getAesCrypt($encrypt=''){
//        $encrypt = "0gaa8RYZrtsI8ytUFL7Rx3KIQNxcYOvy6dXAw5ZKR1LRzie51Co2A4F+22Qy/Gz51mygP/UXmFNQxcfOYrayLUpBoZvxQDBTfwTpKCUNkwh0oBJqYeJ/VdRefvnF5KLNLOPsgAwTRh5P8mvwSeWRt2UCCZS1DVCPtmm+lF1VrBADweGbd/EhUBr2/7CoGeyS";
//        $secret = "WzuOU64dsJicfnt8";//测试
        $secret = "5rivF3yI7WHcxr8Y";//正式
        return \CryptUtils::aesDerypt($encrypt, $secret);
    }


    public function get_callbackname($key){
        $arr = [
            'SEND_SIGNING' => '发送签署',
            'SEND_FILLING' => '发送填参',
            'FILLED' => '完成参数',
            'CONFIG_FLOW' => '配置流程',
            'PERSONAL' => '个人签字',
            'OPERATOR' => '经办人签名',
            'LEGAL_PERSON' => '法定代表人签字',
            'SEAL' => '企业签章',
            'AUDIT_SIGN' => '审批并签署',
            'AUDIT' => '文件审批',
            'RECALLED' => '撤回文件',
            'REJECTED' => '退回文件',
            'EXPIRED' => '文件过期',
            'COMPLETE' => '文件完成',
            'SEND_INVALID' => '发送作废',
            'INVALIDING' => '签署作废',
            'INVALIDED' => '作废完成',
            'INVALID_REJECTED' => '拒绝作废',
            'FAILED' => '签署失败',
            'DOCUMENT_DELAY' => '文件延期',
            'MODIFY_SIGNATORY' => '修改接收方信息',
            'UNKNOWN' => '未知',
        ];
        $str = isset($arr[$key]) ? $arr[$key] : '';
        return $str;
    }
}























